// Copyright 2012. InMobi. All Rights reserved

package com.inmobi.sharedlock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 *
 */
public class ThreadSafeCalculator4 implements AverageCalculator {

  private final AtomicInteger atomicFlag = new AtomicInteger(0);

  private final AtomicInteger atomicCount = new AtomicInteger(0);

  private final AtomicInteger atomicCount2 = new AtomicInteger(0);

  private final AtomicLong atomicSum = new AtomicLong(0);

  @Override
  public void addValue(long value) {
    while (atomicFlag.get() != 0) {
      // spin
    }
    atomicCount.incrementAndGet();
    atomicSum.addAndGet(value);
    atomicCount2.incrementAndGet();
  }

  @Override
  public double getAverage() {
    int count;
    long sum;
    int count2;

    atomicFlag.incrementAndGet();
    do {
      count = atomicCount.get();
      sum = atomicSum.get();
      count2 = atomicCount2.get();
    } while (count != count2);
    atomicFlag.decrementAndGet();

    return count != 0 ? (sum * 1.0) / count : 0.0;

  }
}
